package com.alpha.framework.utils;

import java.lang.Thread.UncaughtExceptionHandler;
import java.net.ConnectException;
import java.net.SocketException;
import java.util.concurrent.TimeoutException;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.alpha.framework.application.BaseApplication;

public class UncaughtHandler implements UncaughtExceptionHandler {

	private Thread.UncaughtExceptionHandler mDefaultHandler;
	public static final String TAG = UncaughtHandler.class.getSimpleName();
	private BaseApplication application;

	public UncaughtHandler(BaseApplication application) {
		// 获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		this.application = application;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				Log.e(TAG, "error : ", e);
			}
			Intent intent = new Intent();
			ComponentName comp = new ComponentName(
					"com.slanissue.apps.mobile.erge",
					"com.slanissue.apps.mobile.bevarhymes.SplashActivity");
			intent.setComponent(comp);
			PendingIntent restartIntent = PendingIntent.getActivity(
					application.getApplicationContext(), 0, intent,
					Intent.FLAG_ACTIVITY_NEW_TASK);
			// 退出程序
			AlarmManager mgr = (AlarmManager) application
					.getSystemService(Context.ALARM_SERVICE);
			mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
					restartIntent); // 1秒钟后重启应用

			application.finishActivity();
		}
	}

	/**
	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
	 * 
	 * @param ex
	 * @return true:如果处理了该异常信息;否则返回false.
	 */
	private boolean handleException(final Throwable ex) {
		if (ex == null) {
			return false;
		}
		ex.printStackTrace();
		for( StackTraceElement element : ex.getStackTrace()){
			Log.e("UncaughtHandler",  element.toString());
		}
		// 使用Toast来显示异常信息
		if (ex instanceof SocketException || ex instanceof ConnectException
				|| ex instanceof TimeoutException) {
			Log.e("error", "不是崩溃异常");
			return false;
		}
		new Thread() {
			@Override
			public void run() {
				Log.e("test", "程序异常了");
				Log.e("error", ex.toString());
				Looper.prepare();
				Toast bt = new Toast(
						application.getApplicationContext());
				bt.setDuration(Toast.LENGTH_SHORT);
				bt.setText("很抱歉,程序出现异常,即将退出.");
				bt.show();
				Looper.loop();
			}
		}.start();
		return true;
	}

}
